import React, { useState } from 'react'
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Row,
  Col,
  Typography
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  BookOutlined,
  UnorderedListOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { Option } = Select
const { TextArea } = Input

// 字典类型枚举
const DICT_TYPES = {
  SYSTEM: 1, // 系统字典
  BUSINESS: 2, // 业务字典
  CUSTOM: 3 // 自定义字典
}

// 状态枚举
const STATUS = {
  ENABLED: 1, // 启用
  DISABLED: 0 // 禁用
}

const DictTypeManagement = ({ onViewDictData, onAddDictData }) => {
  const [dictTypes, setDictTypes] = useState([
    {
      id: 1,
      name: '用户状态',
      type: 'user_status',
      dictType: DICT_TYPES.SYSTEM,
      status: STATUS.ENABLED,
      description: '系统用户状态字典',
      createTime: '2023-01-15 10:30:00',
      updateTime: '2023-12-01 14:20:00'
    },
    {
      id: 2,
      name: '性别',
      type: 'gender',
      dictType: DICT_TYPES.SYSTEM,
      status: STATUS.ENABLED,
      description: '性别字典',
      createTime: '2023-02-10 09:15:00',
      updateTime: '2023-11-15 16:30:00'
    },
    {
      id: 3,
      name: '订单状态',
      type: 'order_status',
      dictType: DICT_TYPES.BUSINESS,
      status: STATUS.ENABLED,
      description: '订单业务状态字典',
      createTime: '2023-03-20 14:25:00',
      updateTime: '2023-12-05 10:45:00'
    },
    {
      id: 4,
      name: '通知类型',
      type: 'notice_type',
      dictType: DICT_TYPES.BUSINESS,
      status: STATUS.ENABLED,
      description: '系统通知类型字典',
      createTime: '2023-04-05 11:30:00',
      updateTime: '2023-11-20 15:20:00'
    }
  ])

  const [modalVisible, setModalVisible] = useState(false)
  const [editingDict, setEditingDict] = useState(null)
  const [form] = Form.useForm()

  // 获取字典类型文本
  const getDictTypeText = type => {
    switch (type) {
      case DICT_TYPES.SYSTEM:
        return '系统字典'
      case DICT_TYPES.BUSINESS:
        return '业务字典'
      case DICT_TYPES.CUSTOM:
        return '自定义字典'
      default:
        return '未知'
    }
  }

  // 获取字典类型颜色
  const getDictTypeColor = type => {
    switch (type) {
      case DICT_TYPES.SYSTEM:
        return 'blue'
      case DICT_TYPES.BUSINESS:
        return 'green'
      case DICT_TYPES.CUSTOM:
        return 'orange'
      default:
        return 'default'
    }
  }

  // 获取状态文本
  const getStatusText = status => {
    return status === STATUS.ENABLED ? '启用' : '禁用'
  }

  // 获取状态颜色
  const getStatusColor = status => {
    return status === STATUS.ENABLED ? 'green' : 'red'
  }

  // 字典类型表格列
  const columns = [
    {
      title: '字典名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <span>
          <BookOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          {text}
        </span>
      )
    },
    {
      title: '字典类型',
      dataIndex: 'type',
      key: 'type',
      render: text => <Tag color='blue'>{text}</Tag>
    },
    {
      title: '字典分类',
      dataIndex: 'dictType',
      key: 'dictType',
      render: type => (
        <Tag color={getDictTypeColor(type)}>{getDictTypeText(type)}</Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size='middle'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => handleEditDict(record)}
          >
            编辑
          </Button>
          <Button
            type='link'
            icon={<UnorderedListOutlined />}
            onClick={() => onViewDictData(record)}
          >
            查看数据
          </Button>
          <Button
            type='link'
            icon={<PlusOutlined />}
            onClick={() => onAddDictData(record)}
          >
            添加数据
          </Button>
          <Popconfirm
            title='确定要删除这个字典类型吗？'
            onConfirm={() => handleDeleteDict(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 添加字典类型
  const handleAddDict = () => {
    setEditingDict(null)
    form.resetFields()
    setModalVisible(true)
  }

  // 编辑字典类型
  const handleEditDict = dict => {
    setEditingDict(dict)
    form.setFieldsValue(dict)
    setModalVisible(true)
  }

  // 删除字典类型
  const handleDeleteDict = id => {
    setDictTypes(dictTypes.filter(item => item.id !== id))
    message.success('字典类型删除成功')
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingDict) {
      // 编辑
      setDictTypes(
        dictTypes.map(item =>
          item.id === editingDict.id
            ? { ...item, ...values, updateTime: new Date().toLocaleString() }
            : item
        )
      )
      message.success('字典类型更新成功')
    } else {
      // 新增
      const newDict = {
        id: Math.max(...dictTypes.map(d => d.id)) + 1,
        ...values,
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
      setDictTypes([...dictTypes, newDict])
      message.success('字典类型创建成功')
    }
    setModalVisible(false)
  }

  return (
    <Card>
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between'
        }}
      >
        <Title level={4} style={{ margin: 0 }}>
          字典类型管理
        </Title>
        <Button type='primary' icon={<PlusOutlined />} onClick={handleAddDict}>
          新增字典类型
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={dictTypes}
        rowKey='id'
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条记录`
        }}
      />

      {/* 字典类型模态框 */}
      <Modal
        title={editingDict ? '编辑字典类型' : '新增字典类型'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='name'
                label='字典名称'
                rules={[{ required: true, message: '请输入字典名称' }]}
              >
                <Input placeholder='请输入字典名称' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='type'
                label='字典类型'
                rules={[{ required: true, message: '请输入字典类型' }]}
              >
                <Input placeholder='请输入字典类型（英文）' />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name='dictType'
            label='字典分类'
            rules={[{ required: true, message: '请选择字典分类' }]}
          >
            <Select placeholder='请选择字典分类'>
              <Option value={DICT_TYPES.SYSTEM}>系统字典</Option>
              <Option value={DICT_TYPES.BUSINESS}>业务字典</Option>
              <Option value={DICT_TYPES.CUSTOM}>自定义字典</Option>
            </Select>
          </Form.Item>

          <Form.Item name='status' label='状态' valuePropName='checked'>
            <Switch
              checkedChildren='启用'
              unCheckedChildren='禁用'
              defaultChecked
            />
          </Form.Item>

          <Form.Item name='description' label='描述'>
            <TextArea rows={3} placeholder='请输入字典描述' />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingDict ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}

export default DictTypeManagement
